//!----------------------------------------------------------
//! toobject.js
//!----------------------------------------------------------

// Use this jquery extension to convert the inputs on the selected node(s) into a javascript object
(function ($) {
    $.fn.ToObject = function () {

        var obj = {};

        // List of control names that have been seen.
        var namesSeen = [];

        // inputs
        $('input', this).each(function (index) {
            var nodeToCopy = $(this);

            // do not process controls with the noSubmit class
            // do not process buttons
            if (nodeToCopy.hasClass('noSubmit') || nodeToCopy.attr('type') == 'button') {
                return;
            }

            var name = nodeToCopy.attr('name');
            if (!name || name.length == 0) return; // Don't bother with inputs with no names

            // Only deal with inputs we haven't seen yet
            if (!namesSeen[name]) {

                var value;

                if (nodeToCopy.attr('type') == 'checkbox') {
                    if (nodeToCopy.is(':checked')) {
                        value = true;
                    } else {
                        value = false;
                    }
                } else if (nodeToCopy.attr('type') == 'radio') {
                    if (nodeToCopy.is(':checked')) {
                        value = nodeToCopy.val();
                    } else {
                        // pretend we haven't seen un-selected radio buttons so we end up with the selected one
                        return;
                    }
                } else {
                    value = nodeToCopy.val();
                }

                namesSeen[name] = true;

                obj[name] = value;
            }
        });

        // dropdowns
        $('select', this).each(function (index) {
            var nodeToCopy = $(this);

            // do not process controls with the noSubmit class
            if (nodeToCopy.hasClass('noSubmit')) {
                return;
            }
            
            obj[nodeToCopy.attr('name')] = nodeToCopy.val();
        });
        
        return obj;
    };
    
    $.fn.serializeObject = function()
    {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
})(jQuery);